import '@ant-design/compatible/assets/index.css';
import {
  Button,
  Form,
  Input,
  message,
  Modal,
  Select,
  Checkbox,
  Radio,
  TreeSelect,
  Tabs,
} from 'antd';
import { FormInstance } from 'antd/lib/form';
import { connect } from 'dva';
import React, { PureComponent } from 'react';
import permissonStyle from './index.less';

const FormItem = Form.Item;
const RadioGroup = Radio.Group;
const CheckboxGroup = Checkbox.Group;
const mapStateToProps = (state: any) => ({
  tenant: state.account,
  // loading: state.loading.effects['account/postObjWithRes'],
});
class EditAccountModal extends PureComponent<any, any> {
  formRef = React.createRef<FormInstance>();

  constructor(props: any) {
    super(props);
    this.state = {
      orgValue: [],
      roleRequired: true,
      selectAllOptions: [
        { value: 0, label: '部分数据权限' },
        { value: 1, label: '全量数据权限' },
      ],
      activeTabKey: 'brand',
      tabDisabled: false,
      postSelectAll: 0,
      brand: [],
      project: [],
      person: [],
      brandPermisionData: [],
      projectPermisionData: [],
      personPermisionData: [],
      brandCheckAll: false,
      projectCheckAll: false,
      personCheckAll: false,
    };
  }

  //  获取租户管理员账户权限数据
  getPermissionData = (type = 0, sid = '') => {
    //  type: 0 新增, 1 编辑; sid: 租户id
    const { dispatch } = this.props;
    let params: any = {
      operate: type,
    };
    if (type === 1) {
      params.accountSid = sid;
    }
    dispatch({
      type: 'http/getDataWithRes',
      payload: {
        url: '/account/getPermission',
        ...params,
      },
      callback: (res: any) => {
        // console.log('权限数据---', res)
        if (res.statusCode === '0') {
          // this.formatPermisionData(res.data, type)
        }
      },
    });
  };

  formatPermisionData = (data: any, type: any) => {
    if (!(data && data.length > 0)) return;
    let tempBrandPermisionData: Array<any> = [];
    let tempProjectPermisionData: Array<any> = [];
    let tempPersonPermisionData: Array<any> = [];
    let tempBrand: Array<any> = [];
    let tempProject: Array<any> = [];
    let tempPerson: Array<any> = [];
    data.forEach((item: any) => {
      const { sid, itemLevel, used } = item;
      const permisionItem = {
        value: sid,
        label: itemLevel,
      };
      if (item.itemType === 'BRAND') {
        tempBrandPermisionData.push(permisionItem);
        if (type === 1 && used === 1) {
          tempBrand.push(sid);
        }
        return;
      }
      if (item.itemType === 'PROJECT') {
        tempProjectPermisionData.push(permisionItem);
        if (type === 1 && used === 1) {
          tempProject.push(sid);
        }
        return;
      }
      if (item.itemType === 'PERSON') {
        tempPersonPermisionData.push(permisionItem);
        if (type === 1 && used === 1) {
          tempPerson.push(sid);
        }
        return;
      }
    });
    let tempBrandCheckAllStatus =
      tempBrandPermisionData.length > 0 && tempBrand.length === tempBrandPermisionData.length;
    let tempProjectCheckAllStatus =
      tempProjectPermisionData.length > 0 && tempProject.length === tempProjectPermisionData.length;
    let tempPersonCheckAll =
      tempPersonPermisionData.length > 0 && tempPerson.length === tempPersonPermisionData.length;
    let tempSelectAll =
      tempBrandCheckAllStatus && tempProjectCheckAllStatus && tempPersonCheckAll ? 1 : 0;
    this.formRef.current?.setFieldsValue({
      isSelectAll: tempSelectAll,
    });

    this.setState({
      brand: tempBrand,
      project: tempProject,
      person: tempPerson,
      brandPermisionData: tempBrandPermisionData,
      projectPermisionData: tempProjectPermisionData,
      personPermisionData: tempPersonPermisionData,
      brandCheckAll: tempBrandCheckAllStatus,
      projectCheckAll: tempProjectCheckAllStatus,
      personCheckAll: tempPersonCheckAll,
      postSelectAll: tempSelectAll,
      tabDisabled: tempSelectAll === 1 ? true : false,
    });
  };

  componentDidMount() {
    this.props.onRef(this);
  }

  setData = (record) => {
    // console.log('setData-----', record)
    setTimeout(() => {
      this.getPermissionData(1, record.sid);
      const fillFileds = {
        sid: record.sid,
        accountName: record.accountName,
        // orgSid: record.orgSid,
        // roleCodes: record.roleCodes ? record.roleCodes.split(',') : [],
      };
      if (record.accountType === 0) {
        this.setState({
          roleRequired: true,
        });
      } else {
        this.setState({
          roleRequired: false,
        });
      }
      this.formRef.current?.setFieldsValue(fillFileds);
    }, 10);
  };

  saveAccount = () => {
    this.formRef.current?.submit();
  };

  ok = (values: any) => {
    const { dispatch, formValues, pageObj } = this.props;
    const { brand, project, person, brandCheckAll, projectCheckAll, personCheckAll } = this.state;
    //  [...brand, ...project, ...person].length > 0
    const obj = {
      ...values,
      isSelectAll: brandCheckAll && projectCheckAll && personCheckAll ? 1 : 0,
    };
    if (brand.length === 0 && project.length === 0 && person.length === 0) {
      message.error('请至少选择一项权限！');
      return;
    }
    obj.permissionList = {
      brand,
      project,
      person,
    };
    dispatch({
      type: 'account/postObjWithRes',
      payload: {
        url: '/account/edit',
        ...obj,
      },
      callback: (response: any) => {
        if (response.statusCode === '0') {
          /* let params = { ...formValues, page: pageObj.current, size: pageObj.pageSize };
          this.close();
          message.success('编辑成功');
          dispatch({
            type: 'account/postFetchPage',
            payload: {
              url: '/account/findbypage',
              ...params,
            },
          }); */
        }
      },
    });
  };

  close = () => {
    // this.formRef.current?.resetFields();
    const { closeModal } = this.props;
    closeModal();
  };

  onSelectAllChange = (e: any) => {
    if (e.target.value === 1) {
      const { brandPermisionData, projectPermisionData, personPermisionData } = this.state;
      const tempBrand = brandPermisionData.map(function (item: any) {
        return item.value;
      });
      const tempProject = projectPermisionData.map(function (item: any) {
        return item.value;
      });
      const tempPerson = personPermisionData.map(function (item: any) {
        return item.value;
      });

      this.setState({
        activeTabKey: 'brand',
        tabDisabled: true,
        brand: tempBrand,
        project: tempProject,
        person: tempPerson,
        brandCheckAll: true,
        projectCheckAll: true,
        personCheckAll: true,
      });
    } else {
      this.setState({
        tabDisabled: false,
      });
    }
  };

  onBrandCheckChange = (list: any) => {
    const { brandPermisionData } = this.state;
    this.setState({
      brandCheckAll: list.length === brandPermisionData.length,
      brand: list,
    });
  };

  /* setPostSelectAll() {
    const { brand, project, person, brandPermisionData, projectPermisionData, personPermisionData } = this.state
    let val = brandPermisionData.length === brand.length && projectPermisionData.length === project.length && personPermisionData.length === person.length ? 1 : 0;
    this.setState({
      postSelectAll: val
    })
  } */

  onBrandCheckAllChange = (e: any) => {
    const { brandPermisionData } = this.state;
    // console.log(e)
    let tempCheckList: Array<any> = [];
    if (e.target.checked) {
      brandPermisionData.forEach((item: any) => {
        tempCheckList.push(item.value);
      });
    }
    this.setState({
      brandCheckAll: e.target.checked,
      brand: tempCheckList,
    });
  };

  onProjectCheckChange = (list: any) => {
    const { projectPermisionData } = this.state;
    this.setState({
      projectCheckAll: list.length === projectPermisionData.length,
      project: list,
    });
  };

  onProjectCheckAllChange = (e: any) => {
    const { projectPermisionData } = this.state;
    let tempCheckList: Array<any> = [];
    if (e.target.checked) {
      projectPermisionData.forEach((item: any) => {
        tempCheckList.push(item.value);
      });
    }
    this.setState({
      projectCheckAll: e.target.checked,
      project: tempCheckList,
    });
  };

  onPersonCheckChange = (list: any) => {
    const { personPermisionData } = this.state;
    this.setState({
      personCheckAll: list.length === personPermisionData.length,
      person: list,
    });
  };

  onPersonCheckAllChange = (e: any) => {
    const { personPermisionData } = this.state;
    let tempCheckList: Array<any> = [];
    if (e.target.checked) {
      personPermisionData.forEach((item: any) => {
        tempCheckList.push(item.value);
      });
    }
    this.setState({
      personCheckAll: e.target.checked,
      person: tempCheckList,
    });
  };

  render() {
    const { modalVisible, roleOption, orgOption, loading } = this.props;
    const {
      roleRequired,
      selectAllOptions,
      activeTabKey,
      tabDisabled,
      brand,
      project,
      person,
      brandPermisionData,
      projectPermisionData,
      personPermisionData,
      brandCheckAll,
      projectCheckAll,
      personCheckAll,
    } = this.state;
    const footer = (
      <div>
        <Button size="small" onClick={this.close}>
          取消
        </Button>
        <Button size="small" onClick={this.saveAccount} type="primary">
          保存
        </Button>
      </div>
    );
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
        md: { span: 16 },
      },
    };
    return (
      <Modal
        style={{ top: 20 }}
        footer={footer}
        title="编辑账号"
        visible={modalVisible}
        onCancel={this.close}
      >
        <Form style={{ marginTop: 12 }} ref={this.formRef} onFinish={this.ok}>
          <FormItem style={{ display: 'none' }} label="sid" name="sid">
            <Input readOnly={true} />
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="登录账号"
            name="accountName"
            rules={[{ required: true, message: '请输入登录账号' }]}
          >
            <Input disabled maxLength={64} placeholder="请输入登录账号" />
          </FormItem>
          {roleRequired && (
            <FormItem
              {...formItemLayout}
              label="角色"
              name="roleCodes"
              rules={[{ required: true, message: '请选择角色' }]}
            >
              <Select
                mode="multiple"
                showSearch
                allowClear
                placeholder="请选择角色"
                optionFilterProp="children"
              >
                {roleOption}
              </Select>
            </FormItem>
          )}
          <Form.Item
            {...formItemLayout}
            name="isSelectAll"
            label="数据权限"
            rules={[{ required: true, message: '请选择' }]}
          >
            <RadioGroup options={selectAllOptions} onChange={this.onSelectAllChange} />
          </Form.Item>
          <Form.Item colon={false} label=" " {...formItemLayout}>
            <div className={permissonStyle.dataPermisionBox}>
              <Tabs
                type="card"
                activeKey={activeTabKey}
                onChange={(key) => {
                  // console.log(key)
                  this.setState({
                    activeTabKey: key,
                  });
                }}
              >
                <Tabs.TabPane disabled={tabDisabled} tab="品牌" key="brand">
                  <Checkbox
                    disabled={tabDisabled}
                    onChange={this.onBrandCheckAllChange}
                    checked={brandCheckAll}
                  >
                    全选
                  </Checkbox>
                  <div>
                    <CheckboxGroup
                      disabled={tabDisabled}
                      options={brandPermisionData}
                      value={brand}
                      onChange={this.onBrandCheckChange}
                    />
                  </div>
                </Tabs.TabPane>
                <Tabs.TabPane disabled={tabDisabled} tab="项目" key="project">
                  <Checkbox
                    disabled={tabDisabled}
                    onChange={this.onProjectCheckAllChange}
                    checked={projectCheckAll}
                  >
                    全选
                  </Checkbox>
                  <div>
                    <CheckboxGroup
                      disabled={tabDisabled}
                      options={projectPermisionData}
                      value={project}
                      onChange={this.onProjectCheckChange}
                    />
                  </div>
                </Tabs.TabPane>
                <Tabs.TabPane disabled={tabDisabled} tab="人员" key="person">
                  <Checkbox
                    disabled={tabDisabled}
                    onChange={this.onPersonCheckAllChange}
                    checked={personCheckAll}
                  >
                    全选
                  </Checkbox>
                  <div>
                    <CheckboxGroup
                      disabled={tabDisabled}
                      options={personPermisionData}
                      value={person}
                      onChange={this.onPersonCheckChange}
                    />
                  </div>
                </Tabs.TabPane>
              </Tabs>
            </div>
          </Form.Item>
          <FormItem {...formItemLayout} label="组织" name="orgSid">
            <TreeSelect
              showSearch
              filterTreeNode={(val, treeNode) => {
                return treeNode.props.title.indexOf(val) >= 0;
              }}
              treeData={orgOption}
              dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
              placeholder="请选择组织"
              showCheckedStrategy="SHOW_ALL"
              allowClear
              treeDefaultExpandAll
            />
          </FormItem>
        </Form>
      </Modal>
    );
  }
}
export default connect(mapStateToProps)(EditAccountModal);
